
from django_redis import get_redis_connection
import json

from utils.cookiesecret import CookieSecret


# 封装 购物车合并
def merge_cart_cookie_to_redis(request, user,response):
    # 1.cookie_dict 数据
    cookie_str = request.COOKIES.get('carts')

    if cookie_str:
        cookie_dict = CookieSecret.loads(cookie_str)
    else:

        return response

    # 2.redis_dict 数据
    redis_client = get_redis_connection('carts')
    redis_data = redis_client.hgetall(user.id)
    redis_dict = {int(data[0].decode()): json.loads(data[1].decode()) for data in redis_data.items()}

    # 3.覆盖 字典 update()
    redis_dict.update(cookie_dict)

    # 4.遍历更新redis
    for sku_id in redis_dict.keys():
        redis_client.hset(user.id, sku_id, json.dumps(redis_dict[sku_id]))


    # 5.删除cookie的数据
    response.delete_cookie('carts')

    return response
